/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.sociesc.indoorgps.dao;

import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;
import com.sociesc.indoorgps.User;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * @author guilherme
 */
public class Dao<T> {
    
    private Class objClazz;
    public Dao(Class clazz){
        this.objClazz = clazz;
    }

    
    public T create(T obj) throws SQLException{
        ConnectionSource conn = ConnectionFactory.createConn();
        com.j256.ormlite.dao.Dao<T,Integer> ormDao = DaoManager.createDao(conn, this.objClazz);
        ormDao.create(obj);
        conn.close();
        return obj;
    }
    
    public T update(T obj) throws SQLException{
        ConnectionSource conn = ConnectionFactory.createConn();
        com.j256.ormlite.dao.Dao<T,Integer> ormDao = DaoManager.createDao(conn, this.objClazz);
        ormDao.update(obj);
        conn.close();
        return obj;
    }
    
    public T findById(Integer id) throws SQLException{
        ConnectionSource conn = ConnectionFactory.createConn();
        com.j256.ormlite.dao.Dao<User,Integer> ormDao = DaoManager.createDao(conn, User.class);
        T obj = (T) ormDao.queryForId(id);
        conn.close();
        return obj;
    }
    
    public List<T> findAll() throws SQLException{
        ConnectionSource conn = ConnectionFactory.createConn();
        com.j256.ormlite.dao.Dao<User,Integer> ormDao = DaoManager.createDao(conn, User.class);
        List<T> users = (List<T>) ormDao.queryForAll();
        conn.close();
        return users;
    }
    
}
